<template>
  <div class="combo-detail-page" >
    <el-main class="main-content">
      <h2 class="page-title">{{ activity.name }} - 套餐活动详情</h2>
      
      <!-- Activity Info -->
      <el-card class="activity-info-card" shadow="hover">
        <div class="activity-info">
          <h3 class="activity-title">{{ activity.name }}</h3>
          <p class="info-item">活动时间: {{ formatDate(activity.startTime) }} - {{ formatDate(activity.endTime) }}</p>
          <p class="info-item">状态: {{ getActivityStatus(activity.status) }}</p>
          <p class="info-item">套餐价格: {{ payAmount }}</p>
        </div>
      </el-card>

      <!-- Combo Items -->
      <h3 class="section-title">套餐商品</h3>
      <el-row :gutter="20" class="combo-items-grid">
        <el-col :span="6" v-for="item in comboItems" :key="item.skuId" class="combo-item-card">
          <el-card :body-style="{ padding: '0px' }" shadow="hover">
            <div class="item-content">
              <img :src="item.skuImage || item.spuMainImage || '/default-image.jpg'" class="item-image" alt="商品图片" />
              <div class="item-info">
                <h4 class="item-title">{{ item.skuName || '未知商品' }}</h4>
                <p class="item-price">单价: ¥{{ item.skuPrice }}</p>
                <p class="item-quantity">数量: {{ item.quantity }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div class="order-summary">
        <p>套餐原价: ¥{{ totalAmount }}</p>
        <p>优惠金额: ¥{{ promotionAmount }}</p>
        <p>套餐价: ¥{{ payAmount }}</p>
        <el-button
          type="danger"
          :disabled="comboItems.length === 0 || isSubmittingOrder || activity.status !== 1"
          :loading="isSubmittingOrder"
          @click="placeOrder"
        >立即购买</el-button>
      </div>
      <!-- Pagination -->
      <div class="pagination" v-if="itemTotal > itemPageSize">
        <el-pagination
          v-model:current-page="itemCurrentPage"
          v-model:page-size="itemPageSize"
          :total="itemTotal"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleItemPageSizeChange"
          @current-change="handleItemPageChange"
        />
      </div>
    </el-main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getComboActivity, getComboItems, placeComboOrder } from '@/api/promotion';
import { useUserInfoStore } from '@/stores/userInfo';

const userInfoStore = useUserInfoStore();
const route = useRoute();
const router = useRouter();
const activityId = ref(route.params.promotionId);
const comboId = ref(1); // 从查询参数获取 comboId
const activity = ref({});
const comboItems = ref([]);
const itemCurrentPage = ref(1);
const itemPageSize = ref(10);
const itemTotal = ref(0);
const isSubmittingOrder = ref(false);

const totalAmount = computed(() => {
  return comboItems.value.reduce((sum, item) => sum + item.skuPrice * item.quantity, 0).toFixed(2);
});

const payAmount = computed(() => {
  return comboItems.value[0]?.comboPrice?.toFixed(2) || '0.00';
});

const promotionAmount = computed(() => {
  return (totalAmount.value - payAmount.value).toFixed(2);
});

const fetchActivity = async () => {
  try {
    const response = await getComboActivity(activityId.value);
    comboId.value = response.data.data.comboId
    console.log(response)
    if (response.data.code === "0" || response.data.code === "200") {
      activity.value = response.data.data;
    } else {
      ElMessage.error(response.data.message || '获取套餐活动失败');
    }
  } catch (error) {
    ElMessage.error('获取套餐活动失败');
    console.error('fetchActivity error:', error);
  }
};

const fetchComboItems = async (page = 1, size = 10) => {
  try {
    const response = await getComboItems(activityId.value, page, size);
    console.log(response)
    if (response.data.code === "0" || response.data.code === "200") {
      const combos = response.data.data.records;
      console.log(combos)
      const selectedCombo = combos.find(combo => combo.id == comboId.value);
      if (selectedCombo) {
        comboItems.value = selectedCombo.items.map(item => ({
          ...item,
          skuPrice: item.skuPrice || 0 // 假设后端返回sku价格
        }));
        comboItems.value.forEach(item => {
          item.comboPrice = selectedCombo.comboPrice; // 存储套餐价格
        });
        itemTotal.value = selectedCombo.items.length;
      } else {
        comboItems.value = [];
        itemTotal.value = 0;
      }
      itemCurrentPage.value = page;
      itemPageSize.value = size;
    } else {
      ElMessage.error(response.data.message || '获取套餐商品失败');
    }
  } catch (error) {
    ElMessage.error('获取套餐商品失败');
    console.error('fetchComboItems error:', error);
  }
};

const placeOrder = async () => {
  if (!userInfoStore.userInfo.id) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }
  if (comboItems.value.length === 0) {
    ElMessage.error('套餐商品为空');
    return;
  }
  try {
    isSubmittingOrder.value = true;
    const response = await placeComboOrder(userInfoStore.userInfo.id,
activityId.value,comboId.value
    );
    if (response.data.code === "0" || response.data.code === "200") {
      ElMessage.success(response.data.data.message);
      router.push({ path: '/pay/choose', query: { orderSn: response.data.data.orderSn } });
    } else {
      ElMessage.error(response.data.message || '下单失败');
    }
  } catch (error) {
    ElMessage.error('下单失败');
    console.error('placeOrder error:', error);
  } finally {
    isSubmittingOrder.value = false;
  }
};

const handleItemPageChange = async () => {
  await fetchComboItems(itemCurrentPage.value, itemPageSize.value);
};

const handleItemPageSizeChange = async () => {
  itemCurrentPage.value = 1;
  await fetchComboItems(1, itemPageSize.value);
};

const getActivityStatus = (status) => {
  const statuses = { 0: '停用', 1: '启用' };
  return statuses[status] || '未知';
};

const formatDate = (dateStr) => {
  return dateStr ? new Date(dateStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }) : 'N/A';
};

const parseScope = (scopeJson) => {
  try {
    const scope = JSON.parse(scopeJson || '[]');
    return scope.length ? scope.join(', ') : '无';
  } catch {
    return '无法解析';
  }
};

const parseConfig = (configJson) => {
  try {
    return JSON.stringify(JSON.parse(configJson || '{}'), null, 2);
  } catch {
    return '无';
  }
};

onMounted(async () => {
  await Promise.all([
    fetchActivity(),
    fetchComboItems()
  ]);
});
</script>

<style scoped>
.combo-detail-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 24px;
  text-align: center;
}

.main-content {
  margin: 24px 0;
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 48px);
}

.activity-info-card {
  margin-bottom: 24px;
  border-radius: 12px;
}

.activity-info {
  padding: 16px;
}

.activity-title {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
}

.info-item {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin: 24px 0 16px;
}

.combo-items-grid {
  margin-bottom: 24px;
}

.combo-item-card .el-card {
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
}

.combo-item-card .el-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.15);
}

.item-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
}

.item-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  margin-bottom: 12px;
}

.item-info {
  text-align: center;
  width: 100%;
}

.item-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

.item-price {
  font-size: 14px;
  color: #f56c6c;
  font-weight: 500;
  margin-bottom: 4px;
}

.item-quantity {
  font-size: 14px;
  color: #606266;
}

.order-summary {
  margin: 20px 0;
  text-align: right;
}

.order-summary p {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.order-summary .el-button {
  margin-top: 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}
</style>